<template>
  <div class="edit-container">
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
    >
      <el-form-item label="套餐名称：" prop="name">
        <el-input v-model="ruleForm.name" placeholder="请选择套餐名称" />
      </el-form-item>
      <el-form-item label="套餐分类：" prop="categoryId">
        <el-select v-model="ruleForm.categoryId" placeholder="请选择套餐分类">
          <el-option
            v-for="item in setmealNameList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="套餐价格：" prop="price">
        <el-input
          v-model.number="ruleForm.price"
          placeholder="请选择套餐价格"
        />
      </el-form-item>
      <el-form-item label="套餐菜品:" class="setmealFood">
        <el-form-item>
          <div class="addDish">
            <el-button
              v-if="ruleForm.setmealDishes.length == 0"
              class="addBut"
              @click="openAddDish"
              icon="el-icon-plus"
            >
              添加菜品</el-button
            >
            <div v-if="ruleForm.setmealDishes.length != 0" class="content">
              <el-button
                class="addBut"
                style="margin-bottom: 20px"
                @click="openAddDish"
                icon="el-icon-plus"
              >
                添加菜品
              </el-button>
              <div class="table">
                <el-table :data="ruleForm.setmealDishes" style="width: 100%">
                  <el-table-column
                    prop="label"
                    label="名称"
                    width="180"
                    align="center"
                  ></el-table-column>
                  <el-table-column prop="price" label="原价" width="180">
                    <template slot-scope="scope">
                      {{ Number(scope.row.price) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="address" label="份数" align="center">
                    <template slot-scope="scope">
                      <el-input-number
                        v-model="scope.row.copies"
                        size="small"
                        :min="1"
                        :max="99"
                        label="描述文字"
                      ></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="address"
                    label="操作"
                    width="180px;"
                    align="center"
                  >
                    <template slot-scope="scope">
                      <el-button
                        type="text"
                        size="small"
                        @click="delDishHandle(scope.$index)"
                      >
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form-item>
      <el-form-item label="套餐图片：" prop="image">
        <el-upload
          class="upload-demo"
          action="/dev-api/common/upload"
          :on-success="handleSuccess"
          :on-exceed="handleExceed"
          list-type="picture-card"
          :file-list="fileList"
          :limit="1"
        >
          <i slot="default" class="el-icon-plus" />
          <div slot="file" slot-scope="{ file }">
            <img
              class="el-upload-list__item-thumbnail"
              :src="file.url"
              alt=""
            />
            <span class="el-upload-list__item-actions">
              <span
                class="el-upload-list__item-preview"
                @click="handlePreview(file)"
              >
                <i class="el-icon-zoom-in" />
              </span>
              <span
                v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
              >
                <i class="el-icon-delete" />
              </span>
            </span>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="套餐描述：" prop="description">
        <el-input
          v-model="ruleForm.description"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4 }"
          placeholder="套餐描述，最长200字"
        />
      </el-form-item>
      <el-form-item class="btn">
        <el-button class="cancelBtn" @click="$router.go(-1)">取消</el-button>
        <el-button class="saveBtn" @click="submitForm('ruleForm')"
          >保存</el-button
        >
        <el-button
          class="saveAddBtn"
          @click="submitForm('ruleForm')"
          v-if="myType === 'add'"
          >保存并添加</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 添加菜品的弹出框 -->
    <el-dialog
      title="添加菜品"
      class="addDishList"
      :visible.sync="adddialogVisible"
      width="60%"
      :before-close="handleClose"
    >
      <el-input
        v-model="value"
        class="seachDish"
        placeholder="请输入菜品名称进行搜索"
        style="width: 250px"
        size="small"
        clearable
      >
        <i
          slot="prefix"
          class="el-input__icon el-icon-search"
          style="cursor: pointer"
          @click="seachHandle"
        ></i>
      </el-input>
      <!-- <AddDish ref="adddish" :check-list="checkList" :seach-key="seachKey" @checkList="getCheckList" /> -->

      <div class="addDishCon">
        <div class="leftCont">
          <div v-show="seachKey.trim() == ''" class="tabBut">
            <span
              v-for="(item, index) in dishType"
              :key="index"
              :class="{ act: index == keyInd }"
              @click="checkTypeHandle(index, item.id)"
              >{{ item.name }}</span
            >
          </div>
          <div class="tabList">
            <div class="table">
              <div v-if="dishAddList.length == 0" style="padding-left: 10px">
                暂无菜品!
              </div>
              <el-table
                ref="multipleTable"
                :data="dishAddList"
                style="width: 100%"
                row-key="dishId"
                @selection-change="handleSelectionChange"
                v-else
                highlight-selection-row="false"
                :row-class-name="
                  ({ row }) =>
                    checkedList.some(item => item.dishId === row.dishId)
                      ? 'selected-row'
                      : ''
                "
              >
                <el-table-column type="selection" reserve-selection>
                </el-table-column>
                <el-table-column
                  prop="name"
                  label="菜品名称"
                  align="center"
                ></el-table-column>
                <el-table-column label="售卖状态" align="center">
                  <template slot-scope="scope">
                    {{ scope.row.status === 0 ? '停售' : '启售' }}
                  </template>
                </el-table-column>
                <el-table-column label="份数" align="center">
                  <template slot-scope="scope">
                    {{ Number(scope.row.price) / 100 }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
        <div class="ritCont">
          <div class="tit">已选菜品({{ checkedList.length }})</div>
          <div class="items">
            <span v-for="(item, ind) in checkedList" :key="ind" class="item">
              <span>{{ item.dishName }}</span>
              <span class="price">￥ {{ Number(item.price) / 100 }} </span>
              <span class="del" @click="delCheck(ind)">
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="addTableList">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 图片点击预览的弹出框 -->
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
      <span slot="footer" class="dialog-footer"> </span>
    </el-dialog>
  </div>
</template>

<script>
import { getCategoryByType } from '@/api/category'
import { editDish, getDishesByCateId } from '@/api/dish'
import { addSetmeal, getSetmealById } from '@/api/setmeal'
import { Message } from 'element-ui'
export default {
  name: 'EditSetmeal',

  beforeRouteEnter (to, from, next) {
    const type = to.params.myType
    if (type === 'add') {
      to.meta.title = '新增套餐'
    } else if (type === 'edit') {
      to.meta.title = '修改套餐'
    }
    next()
  },

  props: {
    myType: {
      type: String,
      default: ''
    }
  },

  data () {
    return {
      ruleForm: {
        // 套餐分类下具体套餐的名称
        name: '',
        // 套餐分类的id
        categoryId: '',
        price: '',
        // 图片
        image: '',
        description: '',
        // 该套餐下的菜品
        setmealDishes: []
      },
      id: '',
      seachKey: '',
      value: '',
      dishType: [],
      dishAddList: [],
      checkedList: [],
      dishListCache: [],
      keyInd: 0,
      searchValue: '',
      checkedList: [],
      adddialogVisible: false,
      dialogVisible: false,
      selectedDishes: [],
      options: [],
      key: 0,
      multipleSelection: [],

      rules: {
        name: [{ required: true, message: '请输入套餐名称', trigger: 'blur' }],
        categoryId: [
          { required: true, message: '请选择套餐分类', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入套餐价格', trigger: 'blur' },
          { type: 'number', message: '套餐价格必须为数字值' }
        ],
        image: [{ required: true, message: '请上传图片', trigger: 'change' }]
      },

      props: {
        multiple: true,
        // 在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
        emitPath: false,
        lazy: true,
        async lazyLoad (node, resolve) {
          // console.log(node)
          let nodes = null
          let res = null
          if (node.root) {
            // 新增前获取所有菜品分类
            res = await getCategoryByType({ type: 1 })
          } else {
            // node.value 为菜品分类的id
            // 根据菜品分类的id获取具体分类的所有菜品
            res = await getDishesByCateId(node.value)
          }
          console.log(res)

          nodes = res.data.map(item => ({
            value: item.id,
            label: item.name,
            price: item.price,
            leaf: node.level === 1
          }))
          resolve(nodes)
        }
      },

      // 控制级联选择器的显示与隐藏
      isShow: false,

      // 已上传的文件的列表
      fileList: [],

      // 新增或编辑前调用接口获取套餐分类
      setmealList: [],

      // 预览图
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false
    }
  },

  computed: {
    setmealNameList () {
      return this.setmealList.map(item => {
        return { name: item.name, id: item.id }
      })
    }
  },

  watch: {
    $route: {
      async handler () {
        // 新增前获取套餐分类
        const res1 = await getCategoryByType({ type: 2 })
        this.setmealList = res1.data
      },
      immediate: true
    },

    'ruleForm.setmealDishes': {
      handler (obj) {
        if (obj.length) {
          this.isShow = true
          this.$nextTick(function () {
            // console.log(this.$refs['cascader'].getCheckedNodes(true))
          })
        } else {
          this.isShow = false
        }
      },
      immediate: true,
      deep: true
    }
  },

  async created () {
    this.getDishTypeList()
    this.getDishType()
    this.id = this.$route.query.id
    this.actionType = this.id ? 'edit' : 'add'
    if (this.myType === 'edit') {
      // console.log(this.id)
      const { data } = await getSetmealById(this.id)
      // console.log(data)
      for (const key in this.ruleForm) {
        if (this.ruleForm['hasOwnProperty'](key)) {
          if (key === 'price') {
            this.ruleForm['price'] = data.price / 100
          } else if (key === 'image') {
            this.fileList.push({
              url:
                process.env.VUE_APP_BASE_API +
                '/common/download?name=' +
                data.image
            })
            this.ruleForm.image = data.image
          } else if (key === 'setmealDishes') {
            this.ruleForm['setmealDishes'] = data.setmealDishes.map(item => ({
              value: item.dishId,
              copies: 1,
              label: item.name,
              price: item.price / 100
            }))
          } else {
            this.ruleForm[key] = data[key]
          }
        }
      }
      // 具体套餐id
      this.ruleForm['id'] = this.id
      /* // 编辑页套餐菜品数据回显
      this.key++
      this.selectedDishes = ['1397854865672679425', '1397853890262118402']
      this.options = ['1397854865672679425', '1397853890262118402'] */
    }
  },

  mounted () {},

  methods: {
    /* 选取图片相关的处理函数 */
    handleRemove () {
      this.fileList.pop()
    },
    handlePreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleSuccess (res, file) {
      // console.log(res)
      this.fileList.push(file)
      if (res.code === 1) {
        this.ruleForm.image = res.data
      }
    },
    handleExceed () {
      Message({
        message: '只能选择一张图片',
        type: 'error',
        duration: 3 * 1000
      })
    },
    seachHandle () {
      this.seachKey = this.value
    },
    // 获取套餐分类
    getDishTypeList () {
      getCategoryByType({ type: 2 }).then(res => {
        if (res.code === 1) {
          this.setMealList = res.data.map(obj => ({ ...obj, idType: obj.id }))
        } else {
          this.$message.error(res.msg || '操作失败')
        }
      })
    },
    // 获取添加菜品数据
    getCheckList (value) {
      this.checkedList = [...value]
      console.log(this.checkedList)
    },

    // 添加菜品
    openAddDish () {
      this.seachKey = ''
      this.adddialogVisible = true
      //搜索条件清空，菜品重新查询，菜品类别选第一个重新查询
      this.value = ''
      this.keyInd = 0
      this.getDishList(this.dishType[0].id)
    },
    // 取消添加菜品
    handleClose (done) {
      // this.$refs.adddish.close()
      this.adddialogVisible = false
      // this.checkList = JSON.parse(JSON.stringify(this.dishTable))
      this.dialogVisible = false
    },

    // 保存添加菜品列表
    addTableList () {
      // 深拷贝避免污染源数据
      this.ruleForm.setmealDishes = this.checkedList.map(item => ({
        ...item,
        copies: item.copies || 1 // 确保份数有默认值
      }))
      this.adddialogVisible = false
    },
    delDishHandle (index) {
      const deleted = this.ruleForm.setmealDishes.splice(index, 1)[0]
      // 从全局列表中移除
      this.checkedList = this.checkedList.filter(
        item => item.dishId !== deleted.dishId
      )
    },
    // 保存并添加
    submitForm (formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          // alert('submit')
          const ruleForm = this.ruleForm
          let finalForm = Object.assign({}, ruleForm, {
            price: ruleForm.price * 100,
            idType: ruleForm.categoryId
          })
          if (this.myType === 'add') {
            finalForm = Object.assign(finalForm, { status: 1, code: '' })
            console.log(finalForm)
            const res = await addSetmeal(finalForm)
            if (res.code === 1) {
              // console.log(res.data)
              Message({
                message: '新增套餐成功！',
                type: 'success',
                duration: 3 * 1000
              })
              // 清空表单
              this.$refs[formName].resetFields()
              // 跳转到 /setmeal/index
              this.$router.push({ path: '/setmeal/index' })
            }
          } else if (this.myType === 'edit') {
            const res = await editDish(finalForm)
            if (res.code === 1) {
              Message({
                message: '修改套餐成功！',
                type: 'success',
                duration: 3 * 1000
              })
              // 清空表单
              this.$refs[formName].resetFields()
              // 跳转到 /setmeal/index
              this.$router.push({ path: '/setmeal/index' })
            }
          }
          // console.log(finalForm)
        } else {
          alert('no')
          return false
        }
      })
    },
    // 获取套餐分类
    getDishType () {
      getCategoryByType({ type: 1 }).then(res => {
        if (res.code === 1) {
          this.dishType = res.data
          this.getDishList(res.data[0].id)
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 删除已选菜品
    delCheck (index) {
      // 获取被删除的菜品对象
      const deletedItem = this.checkedList.splice(index, 1)[0]

      // 同步更新表格选中状态（如果当前分类包含该菜品）
      const targetRow = this.dishAddList.find(
        item => item.dishId === deletedItem.dishId
      )

      if (targetRow) {
        // 取消对应行的选中状态
        this.$refs.multipleTable.toggleRowSelection(targetRow, false)
      }

      // 同步更新表单中的菜品列表（可选，根据具体需求）
      const dishIndex = this.ruleForm.setmealDishes.findIndex(
        item => item.dishId === deletedItem.dishId
      )
      if (dishIndex > -1) {
        this.ruleForm.setmealDishes.splice(dishIndex, 1)
      }
    },
    // 通过套餐ID获取菜品列表分类
    async getDishList (id) {
      const res = await getDishesByCateId(id)
      if (res.code === 1) {
        this.dishAddList = res.data.map(item => ({
          ...item,
          dishId: item.id,
          dishName: item.name,
          copies: 1
        }))

        // 恢复选中状态（包括跨分类的）
        this.$nextTick(() => {
          this.dishAddList.forEach(row => {
            const isChecked = this.checkedList.some(
              checked => checked.dishId === row.dishId
            )
            this.$refs.multipleTable.toggleRowSelection(row, isChecked)
          })
        })
      }
    },
    checkTypeHandle (index, id) {
      this.keyInd = index
      this.getDishList(id)
    },

    handleSelectionChange (val) {
      // 获取当前页选中的菜品ID
      const currentSelectedIds = new Set(val.map(item => item.dishId))

      // 创建新的选中列表：保留其他分类的选中项 + 当前分类的新选中项
      const newCheckedList = [
        ...this.checkedList.filter(
          item => !this.dishAddList.some(d => d.dishId === item.dishId)
        ), // 保留其他分类的选中项
        ...val // 添加当前分类的选中项
      ]

      // 去重处理
      const uniqueMap = new Map()
      newCheckedList.forEach(item => {
        uniqueMap.set(item.dishId, item)
      })
      this.checkedList = Array.from(uniqueMap.values())
    },
    // 获取级联选择器选中的节点
    change () {
      // console.log(this.value)
      // true 代表只获取叶子节点
      this.$nextTick(function () {
        const checkedNodes = this.$refs['cascader'].getCheckedNodes(true)
        // console.log(checkedNodes)
        const setmealDishes = checkedNodes.map(item => ({
          name: item.data.label,
          dishId: item.data.value,
          price: item.data.price,
          copies: 1
        }))
        // console.log(setmealDishes)
        this.ruleForm.setmealDishes = setmealDishes
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';
@import '@/styles/mixin.scss';

.edit-container {
  padding: 20px;
  .setmealFood {
    ::v-deep .el-form-item {
      border: 1px solid $darkorange;
      .el-form-item__content {
        padding: 20px;
        background-color: #fafafb;
      }
    }
  }
  .el-form {
    background-color: $whitecolor;
    padding: 20px;
    border-radius: 4px;

    .el-tag {
      margin-left: 10px;
    }

    .el-input,
    .el-select {
      width: 250px;
    }

    .configDiv {
      border: 1px solid #dfe2e8;
      border-radius: 3px;
      background-color: #fafafb;
      padding: 15px;

      .configRow {
        margin: 10px 0;
        display: flex;

        .el-input:first-of-type {
          flex-basis: 150px;
        }
        .autoWidth {
          flex: auto;
          margin: 0 10px;
        }
      }
    }
  }
  .btn {
    display: flex;
    justify-content: center;
    ::v-deep .el-form-item__content {
      margin-left: 0 !important;
    }
  }
  .addBtn,
  .addBut {
    background-color: $darkorange;
    color: $darkblack;
  }

  .saveBtn {
    background-color: $darkorange;
    color: $darkblack;
    &:hover {
      background-color: $lightorange;
    }
  }
  .saveAddBtn {
    background-color: $darkblack;
    color: #fff;
    &:hover {
      background-color: $lightblack;
    }
  }

  .textColor {
    color: #f56c6c;
  }
  .addDishList {
    .seachDish {
      width: 300px;
      position: absolute;
      top: 10px;
      right: 10px;
      border-radius: 8px;
    }
    .addDishCon {
      display: flex;
      .leftCont {
        display: flex;
        border-right: solid 2px #e4e7ed;
        width: 60%;
        padding: 15px;
        .tabBut {
          width: 110px;
          span {
            width: 112px;
            height: 40px;
            display: block;
            text-align: center;
            line-height: 40px;
            border-right: solid 2px #f4f4f4;
            cursor: pointer;
            font-size: 14px;
          }
          .act {
            border-color: #ffc200 !important;
            color: #ffc200 !important;
          }
        }
        .tabList {
          flex: 1;
          padding: 15px;
          .table {
            border: solid 1px #f4f4f4;
            border-bottom: solid 1px #f4f4f4;
            .items {
              height: 40px;
              border-bottom: solid 1px #f4f4f4;
              padding: 0 10px;
              display: flex;
              line-height: 40px;
              .el-checkbox,
              .el-checkbox__label {
                width: 100%;
                .item {
                  display: flex;
                  padding-right: 20px;
                  span {
                    display: flex;
                    text-align: center;
                    flex: 1;
                  }
                }
              }
            }
          }
        }
      }
      .ritCont {
        width: 40%;
        padding: 0 15px;
        .items {
          margin-top: 15px;
          .item {
            height: 40px;
            line-height: 40px;
            box-shadow: 0px 1px 4px 3px rgba(0, 0, 0, 0.03);
            display: flex;
            text-align: center;
            padding: 0 10px;
            margin-bottom: 20px;
            border-radius: 6px;
            color: #818693;
            span:first-child {
              text-align: left;
              color: #20232a;
            }
            .price {
              display: inline-block;
              flex: 1;
            }
            .del {
              cursor: pointer;
              i {
                position: relative;
                top: 5px;
                width: 20px;
              }
            }
          }
        }
      }
    }
  }
}
</style>
